#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: mysql ddl to yaml
# 实现菜单解析

# import sys

import pymysql

from com.tools.meta import Field

IGNORE_COLS = ["id", "created_at", "updated_at", "deleted_at", "creator"]

# reload(sys)

import importlib, sys


importlib.reload(sys)

# sys.setdefaultencoding('utf8')


class FormatField:
    def __init__(self, table_name):
        self.Fields = []
        self.table_name = table_name
        self.db = pymysql.connect(host="localhost",
                                  user="foxmind",
                                  password="Foxmind0827!",
                                  port=3306,
                                  database="foxmind",
                                  charset='utf8')

        self.cursor = self.db.cursor()

        self.sql = """
        SELECT column_name,data_type,character_maximum_length,is_nullable,column_key,
        replace(column_comment, ' ', '') 
        FROM information_schema.COLUMNS
        where table_schema='foxmind'
        and table_name='%s'
        order by ordinal_position
        """

    def genFields(self):
        try:
            # 执行SQL语句
            self.cursor.execute(self.sql % self.table_name)
            # 获取所有记录列表
            results = self.cursor.fetchall()
            for rows in results:
                # print(rows)
                if rows[0] in IGNORE_COLS:
                    continue
                index = "index" if rows[4] == 'PRI' else ""
                field = Field(name=rows[0], type=rows[1], comment=rows[5], require=rows[3],
                              binding_options="", gorm_options="size: %s;" % rows[2] + index)
                self.Fields.append(field)
        except Exception as e:
            print("Error: unable to fecth data:" + str(e))
        self.cursor.close()
        self.db.close()


if __name__ == '__main__':
    ff = FormatField("t_sale_activity_info")
    ff.genFields()
    for fld in ff.Fields:
        print(fld.__dict__)
